package main

import (
	"context"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"iris_product/common"
	"iris_product/datasource"
	"iris_product/fronted/web/controllers"
	"iris_product/fronted/web/middleware"
	"iris_product/rabbitmq"
	"iris_product/repositories"
	"iris_product/services"
	"log"
)

func main() {
	app := iris.New()
	// 设置日志级别
	app.Logger().SetLevel("debug")
	// 初始化日志
	common.BuildIrisLog(app)
	// 加载模板
	template := iris.HTML("./fronted/web/views",".html").
		Layout("shared/layout.html").Reload(true)
	app.RegisterView(template)
	// 加载静态文件
	app.HandleDir("/public","./fronted/web/public")
	app.HandleDir("/html","./fronted/web/htmlProductShow")
	// 出现异常跳转到指定页面
	app.OnAnyErrorCode(func(ctx iris.Context) {
		ctx.ViewData("message",ctx.Values().GetStringDefault("message","访问的页面出错!"))
		ctx.ViewLayout("")
		ctx.View("shared/error.html")
	})
	// 连接mysql
	db,err := common.NewMysqlConn()
	if err != nil {
		log.Printf("mysql连接错误:" +err.Error())
		return
	}
	// 初始化gorm数据库连接
	datasource.InitGormDb()

	// 初始化Session
	//sess := sessions.New(sessions.Config{
	//	Cookie: "UsersCookie",
	//	Expires: time.Minute * 600,
	//})

	Ctx,cancelFunc := context.WithCancel(context.Background())
	defer cancelFunc()
	repoUser := repositories.NewUserManager("product")
	userService := services.NewUserService(repoUser)
	userParty := app.Party("/user")
	userApp := mvc.New(userParty)
	userApp.Register(Ctx,userService)
	userApp.Handle(new(controllers.UserController))

	repoProduct := repositories.NewProductManager("product",db)
	productService := services.NewProductService(repoProduct)

	// 注入mq
	rabbitmqObj := rabbitmq.NewSimpleRabbitmq("miaosha_order")

	orderRepository := repositories.NewOrderManager("order",db)
	orderService := services.NewOrderService(orderRepository)
	productParty := app.Party("/product",middleware.AuthConProduct)
	productApp := mvc.New(productParty)
	productApp.Register(Ctx,productService,orderService,rabbitmqObj)
	productApp.Handle(new(controllers.ProductController))

	// 启动服务
	app.Run(
		iris.Addr("localhost:8081"),
		// 忽略iris框架的错误
		iris.WithoutServerError(iris.ErrServerClosed),
		// 让程序自身尽可能地进行优化
		iris.WithOptimizations,
	)


}

